package com.jtp7.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jtp7.demo.entity.Permission;
import com.jtp7.demo.entity.User;
import com.jtp7.demo.mapper.UserMapper;
import com.jtp7.demo.service.MyUsersDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("userDetailsService")
public class MyUsersDetailsServiceImpl implements MyUsersDetailsService {

        @Autowired
        private UserMapper userMapper;

        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


//            //调用usersMapper方法，根据用户名查询数据库
//            QueryWrapper<User> wrapper = new QueryWrapper();
//            // where username=?
//            wrapper.eq("username",username);
//            User user = userMapper.selectOne(wrapper);
            User user = userMapper.selectById(username);
            //判断
            if(user == null) {//数据库没有用户名，认证失败
                throw  new UsernameNotFoundException("用户名不存在！");
            } else {
                List<Permission> permissions = userMapper.selectPermissioin(username);

                if (!permissions.isEmpty()) {
                    Set<SimpleGrantedAuthority> sga = new HashSet<>();
                    for (Permission permission : permissions) {
                        sga.add(new SimpleGrantedAuthority(permission.getPermissionCode()));
                    }
                    user.setAuthorities(sga);
                }
            }
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
//            List<GrantedAuthority> auths =
//                    AuthorityUtils.commaSeparatedStringToAuthorityList("guests");

            //从查询数据库返回users对象，得到用户名和密码，返回
            return user;
        }
}
